#!/bin/bash
set -u

APP_CONTENTS="$(cd "$(dirname "$0")/.." && pwd)"
APP_RESOURCES="$APP_CONTENTS/Resources"
PROJECT_DIR="$APP_RESOURCES/BEANalyzer_UltraPro"
APP_SUPPORT="$HOME/Library/Application Support/BEANalyzer UltraPro"
VENV_DIR="$APP_SUPPORT/.venv"
LOG_DIR="$APP_SUPPORT/logs"

# Help Cocoa/Qt identify this process as BEANalyzer instead of the generic Python runtime.
export __CFBundleIdentifier="com.aend-tech.beanalyzer-ultrapro"

mkdir -p "$APP_SUPPORT" "$LOG_DIR"

cd "$PROJECT_DIR"

# Find Homebrew/system Python 3.12 first, then fallback to python3.
PYTHON_BIN=""
for candidate in \
    "/opt/homebrew/opt/python@3.12/bin/python3.12" \
    "/usr/local/opt/python@3.12/bin/python3.12" \
    "/opt/homebrew/bin/python3.12" \
    "/usr/local/bin/python3.12" \
    "/Library/Frameworks/Python.framework/Versions/3.12/bin/python3.12"
do
    if [ -x "$candidate" ]; then
        PYTHON_BIN="$candidate"
        break
    fi
done

if [ -z "$PYTHON_BIN" ]; then
    if command -v python3.12 >/dev/null 2>&1; then
        PYTHON_BIN="$(command -v python3.12)"
    elif command -v python3 >/dev/null 2>&1; then
        PYTHON_BIN="$(command -v python3)"
    fi
fi

if [ -z "$PYTHON_BIN" ]; then
    osascript -e 'display dialog "Python 3.12 was not found. Install it with Homebrew: brew install python@3.12" buttons {"OK"} default button "OK" with icon caution'
    exit 1
fi

# Create external venv in user Application Support, not inside /Applications.
if [ ! -x "$VENV_DIR/bin/python" ]; then
    "$PYTHON_BIN" -m venv "$VENV_DIR"
fi

source "$VENV_DIR/bin/activate"

# Install/update requirements only when the marker is missing or requirements changed.
REQ_HASH_FILE="$APP_SUPPORT/requirements.sha256"
CURRENT_REQ_HASH="$(shasum -a 256 "$PROJECT_DIR/requirements.txt" | awk '{print $1}')"
OLD_REQ_HASH=""
if [ -f "$REQ_HASH_FILE" ]; then
    OLD_REQ_HASH="$(cat "$REQ_HASH_FILE")"
fi

if [ "$CURRENT_REQ_HASH" != "$OLD_REQ_HASH" ]; then
    python -m pip install --upgrade pip setuptools wheel >> "$LOG_DIR/startup.log" 2>&1
    python -m pip install -r "$PROJECT_DIR/requirements.txt" >> "$LOG_DIR/startup.log" 2>&1
    echo "$CURRENT_REQ_HASH" > "$REQ_HASH_FILE"
fi

python "$PROJECT_DIR/beanalyzer_ultrapro.py" >> "$LOG_DIR/runtime.log" 2>&1
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ]; then
    osascript -e "display dialog "BEANalyzer UltraPro closed unexpectedly.\n\nCheck this log file:\n$LOG_DIR/runtime.log\n\nCrash log, if available:\n$LOG_DIR/crash.log" buttons {"OK"} default button "OK" with icon caution" >/dev/null 2>&1 || true
    exit "$EXIT_CODE"
fi
